<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
          <!-- <el-date-picker
            v-model="listQuery.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:00"
            placeholder="选择开始日期"
            style="width: 200px;margin-right:15px;" class="filter-item"
          ></el-date-picker>
          <el-date-picker
            v-model="listQuery.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:00"
            placeholder="选择结束日期"
             style="width: 200px;margin-right:15px;" class="filter-item"
          ></el-date-picker>
        <br/> -->
        <el-input clearable
                    @keyup.enter.native="handleFilter"
                    v-model="listQuery.address"
          style="width: 200px;margin-right:15px;margin-top:7px"
                    class="filter-item"
                    maxlength="20"
                    placeholder="所在城市" />
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button
          class="filter-item"
          type="primary"
          v-waves
          icon="el-icon-circle-plus-outline"
          @click="beforOpenDialog(1)"
          style="width: 100px;margin-right:15px;margin-top:2px"
        >添加</el-button>
    </div>

    <!-- table 表格 -->
    <el-table  :data="list" v-loading="loading.list" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column type='index' label="序号" align="center" width="80px"/>
      <el-table-column  label="所在城市" prop='city' align="center"/>
       <el-table-column label="金额" prop="amountInfo" align="center"/>
       <el-table-column label="时长(天)" prop="timeDay" align="center" />
      <el-table-column label="创建时间" prop="ctime" align="center"/>
      <el-table-column  label="操作"   align="center">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-open"
            @click="beforOpenDialog(2,scope.row)"
            type="primary"
          >编辑</el-button>
             <el-button
            icon="el-icon-open"
            @click="detele(scope.row.cardTypeId)"
            type="danger"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.offset" 
      :page-sizes="[10, 20, 30, 40]" 
      :page-size="listQuery.limit" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>



       <!-- 添加代理商弹窗 -->
    <el-dialog :title="diglogTitle"  :visible.sync="dialog.add">
      <el-form
        :model="addQuery"
        :rules="bindRules"
        ref="ruleForm"
        label-position="right"
        label-width="120px"
        style="textalign:center"
      >
        <el-form-item  label="会员卡类型" prop="cardType">
          <el-select
          :disabled="true"
            v-model="addQuery.cardType"
            placeholder="请选择会员卡类型"
            clearable
            class="filter-item"
            style="width: 200px;"
          >
            <el-option label="城市卡" :value=1></el-option>
            <el-option label="设备卡" :value=2></el-option>
          </el-select>
        </el-form-item>

         <el-form-item  label="所在城市" required >
        <el-form-item  prop="province" style="display:inline-block">
          <el-select
           :disabled="this.dialogType==2"
            clearable
            style="width: 100px;"
            v-model="addQuery.province"
            placeholder="省"
            class="filter-item"
            @change="getCities2(1)"
          >
            <el-option v-for="p in provices" :label="p.NAME" :value="p.AREA_ID" :key="p.AREA_ID"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="city" style="display:inline-block">
          <el-select
            :disabled="this.dialogType==2"
            clearable
            style="width: 100px;"
            v-model="addQuery.city"
            placeholder="市"
            class="filter-item"
            @change="getAreas2(1)"
          >
            <el-option v-for="c in cities" :label="c.NAME" :value="c.AREA_ID" :key="c.AREA_ID"/>
          </el-select>
         </el-form-item>
     </el-form-item>

       <el-form-item label="金额" prop="amount">
          <el-input type="number"   clearable v-model="addQuery.amount" placeholder="请输入充值金额"></el-input>
        </el-form-item>
       <el-form-item label="时长（天数）" prop="timeDay">
          <el-input type="number"  clearable v-model="addQuery.timeDay" placeholder="请输入天数"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">取消</el-button>
        <el-button type="primary" :loading="loading.add" @click="add">确定</el-button>
      </div>
    </el-dialog>
   
 
  </div>
</template>
<script>
import { 
  getAddressByAreaId, 
  getId, 
  getAddress,
  getObjByName,
  getObjByAreaId,
  getByNameProvinceId,
  getByNameCityId,
  getByNameAreaId
} from "@/utils/getAddress";
import { getCardTypeList,addCardType,updateCardType,del} from '@/api/cardType'
import { validatePhone } from '@/utils/validate'
import BackToTop from "@/components/BackToTop";
import VePie from "v-charts/lib/pie";
import { parseTime } from '@/utils'
export default {
  name: 'cardType_list',
   components: {
    BackToTop,
    VePie,
    
  },
  data() {
  var validateAmount = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('金额不能为空!'));      
        }
        setTimeout(() => {
        var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
          if (!isNum.test(value)) {
            callback(new Error('请输入正确金额,金额不能小于0，两位小数以内!'));
          } else {
          if((value+"").length>12){
              callback(new Error('金额超过范围'));
            }
          callback();
          }
        }, 300);
      };

       var validateGiventimeDay = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('时长不能为空!'));      
        }
        setTimeout(() => {
          var isNum= /^(1|([1-9]\d*))$/
          if (!isNum.test(value)) {
            callback(new Error('时长大于0的正整数!'));
          } else {
            if((value+"").length>12){
              callback(new Error('时长超过范围'));
            }
              callback();
          }
        }, 300);
      };
    return {
       provices: [],
      cities: [],
      areas: [],
      pId: '',
      cId: '',
      total: 0,
      dialogType:'',
      agentType:this.$store.state.user.userInfo.managerType,

      // 搜索框信息
      listQuery: {
        offset: 1,
        limit: 10,
        cardType: 2,
        address:'',
      },
      addQuery: {
        cardTypeId:'',
        cardType: '',
        province: '',
        city: '',
        timeDay: '',
        amount:'',
      },
        bindRules: {
           cardType: [
          { required: true, message: "请选择会员卡类型", trigger: "blur" }
        ],
         equipmentType: [
          { required: true, message: "请选择设备类型", trigger: "blur" }
        ],
         province: [
          { required: true, message: "请选择省", trigger: "blur" }
        ],
        city: [
          { required: true, message: "请选择市", trigger: "blur" }
        ],
        amount: [{ required: true,validator: validateAmount, trigger: "blur" }],
        timeDay: [{ required: true,validator: validateGiventimeDay, trigger: "blur" }],

      },
      // 用户状态
       options1:[
        { 
        value:'1',
        label:'正常'
        },
        {
        value:'2',
        label:'禁用'
        }
      ],
       // 用户类型
       options2:[
          {
        value:'1',
        label:'普通用户'
        },
        { 
        value:'2',
        label:'管理员'
        }
      ],
      // 接收的用户列表数据
      list: null,
      // 控制加载动画
      loading: {
        list: false,
        add: false
      },

      dialog:{
        add:false,
        view:false
      },

      downloadLoading: false
    }
  },
  methods: {
   
    //获取用户列表
    async getLists() {
         
      this.loading.list = true
      try {
        const { data } = await getCardTypeList(this.listQuery)
        this.list = data.records.map((item, index) => ({
          index: index + 1,
          address:item.province+ item.city,
          amountInfo:item.amount/100,
           ...item}))
        this.total = data.total
      } catch (error) {
        
      }
      this.loading.list = false     
    },

    //删除
    detele(cardTypeId) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        try {
          const { data } = await del({ cardTypeId });
          this.$message({
            type: "success",
            message: "删除成功"
          });
          this.getLists();
        } catch (error) {}
      });
    },
    //禁用启用
    changeStatus(userId,status) {
      let type;
      if(status){
           type = status == 1 ?"启用":"禁用";
      }else{
         type = "启用";
      }
          
          this.$confirm(`是否${type}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).then(async () => {
              const {data }= await updateIsFlagUsers({
                userId:userId,
                isFlag:status,
              })
              this.$message({
                  type: 'success',
                  message: `${type}成功!`
              });
                this.getLists()
              }).catch(() => {
                    
              });
      }, 

          //添加代理商
    async add() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          try {
    let query = {
            cardTypeId: this.addQuery.cardTypeId,
             cardType: this.addQuery.cardType,
            province: getAddress(this.addQuery.province),
            city: getAddress(this.addQuery.city),
            amount: this.addQuery.amount*100,
            timeDay: this.addQuery.timeDay,
          };

            this.loading.add = true;
         if (this.dialogType === 1) {
          const { data } = await addCardType(query);
         }else{
          const { data } = await updateCardType(query);
         }
            this.$message({
              type: "success",
              message: "操作成功"
            });
            this.dialog.add = false;
            this.loading.add = false;
            this.resetForm();
            this.getLists();
          } catch (error) {
            this.loading.add = false;
           this.resetForm();
          }
        }
      });
    },
 resetForm(flag) {
      this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
      if (flag) {
        this.addQuery = {
          cardTypeId: "",
        };
      }
    },
 beforOpenDialog(type, item) {
  console.log(type, item);
      if (type === 1) {
      this.resetForm();
       this.addQuery.cardType=1
       } else {
        this.resetForm();
        const { cardTypeId, cardType,province,city ,timeDay,amount} = item;
        this.addQuery = { ...this.addQuery,   cardTypeId, cardType,province,city ,timeDay,amount };
        this.addQuery.amount= this.addQuery.amount/100;
        if (province!=null) {
        this.addQuery.province = getByNameProvinceId(province);
        this.addQuery.city = getByNameCityId(province,city);
        }
         this.getCities2();
        this.getAreas2();
      }
      this.dialogType = type;
      this.dialog.add = true;
    },
    
    //搜索
    handleFilter() {
      this.listQuery.offset = 1
      this.getLists()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getLists()
    },
    handleCurrentChange(val) {
      this.listQuery.offset = val
      this.getLists()
    },
   //根据fid 查询省、市、区  fid = 0 查询所有省；查询市或者地区 fid 传对应的省areaID
    getAddressByAreaId(fid) {
      return getAddressByAreaId(fid);
    },
     // 获取对应市
    getCities2(type) {
      if (type) {
        this.addQuery.city = "";
        this.addQuery.area = "";
      }
      this.pId = this.addQuery.province;
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas2(type) {
      if (type) {
        this.addQuery.area = "";
      }
      this.pId = this.addQuery.city;
      this.areas = getAddressByAreaId(this.pId);
    },
    // 获取对应市Id
    getCities() {
      this.addQuery.area = "";
      this.areas = [];
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas() {
      this.addQuery.area = "";
      this.areas = getAddressByAreaId(this.cId);
    }
  },
  //开启页渲染
   created() {
     (this.provices = getAddressByAreaId(0)), this.getCities();
    
   this.getAreas();
    this.getLists();
  
  },
  onLoad(query){
   
  },
   computed: {
    diglogTitle() {
      return this.dialogType === 1 ? "新增" : "编辑";
    }
  }
}
</script>
